package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private HttpSession session;
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findAll(){
        Long user = (Long) session.getAttribute("user");
        List<ShoppingCart> shoppingCartList = shoppingCartService.findAll(user);
        return R.success(shoppingCartList);
    }

    //加入购物车
    @PostMapping("/add")
    public R<String> add(@RequestBody ShoppingCart shoppingCart){
        Long user = (Long) session.getAttribute("user");
        shoppingCart.setUserId(user);

        Boolean flag = shoppingCartService.add(shoppingCart);
        return R.success("添加成功");
    }

    //清空购物车
    @DeleteMapping("/clean")
    public R<String> clean(){
        Long user = (Long) session.getAttribute("user");
        Boolean flag = shoppingCartService.deleteByIds(user);
        if (!flag){
            return R.error("清空失败");
        }

        return R.success("成功");
    }

    //删除购物车指定商品
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart){
        Boolean flag = shoppingCartService.deleteById(shoppingCart);
        return R.success("删除成功");
    }
}
